from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework.renderers import JSONRenderer

from luckin.authentication import TokenAuthentication
from luckin.service.shop_cart import ShopCartService


# 购物车使用redis进行存储数据
# 各个用户的购物车数据使用hash进行存储 key为 shopCart_用户id
# filed为  goods_id(商品id)
# value为  json格式化后的商品信息(通过字典去存储数据)

# 那么get方式请求，则返回该用户购物车的所有数据(hgetall shopCart_用户id)
# 那么post方式请求，hadd
# 那么put方式请求，hset
# 那么delete方法请求,hdel

class ShopCartView(APIView):
    renderer_classes = [JSONRenderer]
    authentication_classes = [TokenAuthentication]

    def get(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shop_cart_service = ShopCartService()
        flag, data = shop_cart_service.get(request)
        if flag:
            response_data["data"] = data
        else:
            response_data["code"] = 400
            response_data["message"] = data

        return Response(status=200, content_type="application/json", data=response_data)

    def post(self, request, *args, **kwargs):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shop_cart_service = ShopCartService()
        flag, message = shop_cart_service.post(request)
        if not flag:
            response_data["code"] = 400

        response_data["message"] = message

        return Response(status=200, content_type="application/json", data=response_data)

    def put(self, request):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shop_cart_service = ShopCartService()
        flag, message = shop_cart_service.put(request)
        if not flag:
            response_data["code"] = 400

        response_data["message"] = message

        return Response(status=200, content_type="application/json", data=response_data)

    def delete(self,request):
        response_data = {
            "code": 200,
            "message": "success"
        }
        shop_cart_service = ShopCartService()
        flag, message = shop_cart_service.delete(request)
        if not flag:
            response_data["code"] = 400
        response_data["message"] = message

        return Response(status=200, content_type="application/json", data=response_data)